
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

export default class Http {
  private baseUrl: string;
  private headers: any; // 添加headers属性

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }
  
  public setHeader(headersParam:any){
	  this.headers = headersParam
  }
  public request<T>(method: HttpMethod, url: string, data?: any, headers?: object): Promise<T> {
    return new Promise((resolve, reject) => {
      uni.request({
        url: this.baseUrl + url,
        method,
        data,
        header: { ...this.headers, ...headers }, // 合并默认headers和自定义headers
        success: (res) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(res.data as T);
          } else {
            reject(new Error(`HTTP 错误! 状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(new Error(`请求失败: ${err.errMsg}`));
        }
      });
    });
  }

  // get<T>(url: string, params?: object): Promise<T> {
  //   const queryString = params ? '?' + new URLSearchParams(params as Record<string, string>).toString() : '';
  //   return this.request<T>('GET', url + queryString);
  // }

  post<T>(url: string, data?: any): Promise<T> {
    return this.request<T>('POST', url, data);
  }

  put<T>(url: string, data?: any): Promise<T> {
    return this.request<T>('PUT', url, data);
  }

  delete<T>(url: string): Promise<T> {
    return this.request<T>('DELETE', url);
  }
}

export const http = new Http('https://erp.uyun-iot.cn');
